// 设置进入各个页面的权限
var releaseExperimentCharacteristic = false;
var gotoExperimentalReportCharacteristic = false;
var gotoNodeManagementCharacteristic = false;
var gotoVideoManagementCharacteristic = false;
var userName = "";
var token = "";

/**
 * 获取用户信息
 * @returns {boolean}
 */

function getUserInfo() {
    var token = getCookie("token");
    $.ajax({
        url: "/apis/user/getUserInfoByToken",
        type: "POST",
        dataType:"json",
        contentType: "application/json;charset=UTF-8",
        headers: {
            token: token //这里是Token
        },
        cache: false,//设置不缓存
        success: getUserSuccess,
        error: showErrorInfo
    });
    return false;
}

/**
 * 函数发生错误时，展示信息
 * @param XMLHttpRequest
 * @param textStatus
 * @param errorThrown
 */
function showErrorInfo(XMLHttpRequest, textStatus,errorThrown) {
    if(XMLHttpRequest.status === 200){
        alert("权限请求出错！错误代码（" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + XMLHttpRequest.responseText + "）");
    }else {
        if (XMLHttpRequest.status >= 400 && XMLHttpRequest.status < 500) {
            alert("客户端请求出错！错误代码（" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + XMLHttpRequest.responseText + "）");
        } else {
            if (XMLHttpRequest.status >= 500 && XMLHttpRequest.status <= 600) {
                alert("服务器出错！错误代码（" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + XMLHttpRequest.responseText + "）");
            } else {
                if (XMLHttpRequest.status >= 300 && XMLHttpRequest.status < 400) {
                    alert("重定向问题！错误代码（" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + XMLHttpRequest.responseText + "）");
                } else {
                    alert("抱歉，系统好像出现一些异常！错误代码（" + XMLHttpRequest.status + "," + XMLHttpRequest.readyState + "," + XMLHttpRequest.responseText + "）");
                }
            }
        }
    }
}


/**
 * 获取用户信息成功之后的处理
 * @param data
 * @returns {boolean}
 */
function getUserSuccess(data) {

    // 判断是否登录
    if(!data.flag) {
        // 当前未登录，将跳转至登录页面
         document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
         document.getElementById("userLogin").click();
    } else {
        // 当前已登录，得到用户信息
        var user = JSON.parse(data.msg);
        userName = user['name'];
        role = user['role'];

        // 判断当前登录的用户是否为教师
        if (role.indexOf("教师") === 0) {

            // 当前登录用户为教师
            teacherGetCoursesTop5();
        } else {

            // 当前登录用户为学生
            document.getElementById("userInfo").innerHTML = "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "我的课程" +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='#'>Linux基础入门新版</a></li>" +
                "<li><a class=''  href='#'>高级bash编程指南</a></li>" +
                "<li><a class=''  href='#'>java实现记事本</a></li>" +
                "<li><a class='' href='#' >python实现文字聊天室</a></li>" +
                "<li><a class=''  href='#'>查看更多</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>" +
                "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "欢迎您，" + userName +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='/home/index.html' >我的主页</a></li>" +
                "<li><a class='' href='#' onclick='signOut(); return false;' data-toggle='modal' data-target='#signOutModel'>退出登录</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>";
        }

        if(releaseExperimentCharacteristic) {
            releaseExperimentCharacteristic = false;
            if(role.indexOf("教师") === 0) {
                window.location.href="/developer/index.html";
            } else {
                alert("抱歉，您的身份是：" + role + "  仅有教师可以发布实验！");
            }
        } else {
            if (gotoExperimentalReportCharacteristic) {
                gotoExperimentalReportCharacteristic = false;
                if (role.indexOf("教师") === 0) {
                    window.location.href = "/experimental_report/index.html";
                } else {
                    alert("抱歉，您的身份是：" + role + "  仅有教师可以查看实验报告！");
                }
            } else {
                if (gotoNodeManagementCharacteristic) {
                    gotoNodeManagementCharacteristic = false;
                    if (role.indexOf("教师") === 0) {
                        window.location.href = "/node_management/index.html";
                    } else {
                        alert("抱歉，您的身份是：" + role + "  仅有教师可以进行节点管理！");
                    }
                }else
                {
                    if (gotoVideoManagementCharacteristic){
                        gotoVideoManagementCharacteristic = false;
                        if(role.indexOf("教师") === 0) {
                            window.location.href = "/video/index.html";
                        } else {
                            alert("抱歉，您的身份是：" + role + "  仅有教师可以进行视频管理！");
                        }
                    }
                }
            }
        }
    }
    return false;
}


/**
 * 用于处理登录
 * @returns {boolean}
 */
function login() {
    var id = document.getElementById("id").value;
    var password = document.getElementById("password").value;
    var checkCode = document.getElementById("checkCode").value;
    if(id === "" || password === "" || checkCode === "") {
        // alert("所有字段不允许为空！");
        document.getElementById("loginError").style.display = "block";
        document.getElementById("loginErrorMessage").innerHTML = "所有字段不可以为空！";
        document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        setTimeout(clearLoginError, 1500);
        return false;
    }
    const obj = {};
    obj.id = id;
    obj.password = password;
    obj.checkCode = checkCode;
    var token = getCookie("token");
    $.ajax({
        url: "/apis/user/login",
        type: "POST",
        cache: false,//设置不缓存
        dataType:"json",
        contentType: "application/json;charset=UTF-8",
        headers: {
            token: token //这里是Token
        },
        data: JSON.stringify(obj),
        success: loginSuccess,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            showErrorInfo(XMLHttpRequest,textStatus,errorThrown);
        }
    });
    return false;
}

/**
 * ajax登录请求成功的回调函数
 * @param data
 * @returns {boolean}
 */
function loginSuccess(data) {
    if(data.flag) {
        setTokenToCookie(data.token);
        getUserInfo();
        document.getElementById("closeLogin").click();
    } else {
        // alert(data);
        document.getElementById("loginError").style.display = "block";
        document.getElementById("loginErrorMessage").innerHTML = data.msg;
        document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        setTimeout(clearLoginError, 1500);
        return false;
    }
}

function clearLoginError() {
    if(document.getElementById("loginError").style.display.indexOf("block") === 0) {
        document.getElementById("loginError").style.display = "none";
        document.getElementById("loginErrorMessage").innerHTML = "";
    }
}

/**
 * 退出登录处理
 */
function signOut() {
    deleteCookie("token");
    if ("no" === getCookie("token")){
        parent.location.reload();
    }else {
        alert("注销失败");
    }
}
/**
 * 进入发布实验页面前的处理
 */
function releaseExperiment() {
    gotoExperimentalReportCharacteristic = false;
    gotoNodeManagementCharacteristic = false;
    gotoVideoManagementCharacteristic = false;
    releaseExperimentCharacteristic = true;
    getUserInfo();
}

/**
 * ajax初始化获取用户信息请求成功后的回调函数
 * @param data
 * @returns {boolean}
 */
function getInitUserSuccess(data) {
    if(!data.flag) {
        // 当前未登录，将跳转至登录页面
         document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
         document.getElementById("userLogin").click();
    } else {
        var user = JSON.parse(data.msg);
        userName = user['name'];
        var role = user['role'];
        if (role.indexOf("教师") === 0) {
            teacherGetCoursesTop5();
        } else {
            var str = "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "我的课程" +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='#'>Linux基础入门新版</a></li>" +
                "<li><a class=''  href='#'>高级bash编程指南</a></li>" +
                "<li><a class=''  href='#'>java实现记事本</a></li>" +
                "<li><a class='' href='#' >python实现文字聊天室</a></li>" +
                "<li><a class=''  href='#'>查看更多</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>" +
                "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "欢迎您，" + userName +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='/home/index.html' >我的主页</a></li>" +
                "<li><a class='' href='#' onclick='javascript:signOut(); return false;' data-toggle='modal' data-target='#signOutModel'>退出登录</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>";
            document.getElementById("userInfo").innerHTML = str;
        }
        setTokenToCookie(data.token)
    }
    return false;
}

function getCoursesTop4() {
    var token = getCookie("token");
    $.ajax({
        url: "/apis/course/get_my_courses_top_number?topNumber=4",
        type: "GET",
        cache: false,//设置不缓存
        headers: {
            token: token //这里是Token
        },
        success: getCoursesTop4Success,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            showErrorInfo(XMLHttpRequest,textStatus,errorThrown);
        }
    });
}

function getCoursesTop4Success(data) {
    var coursesJson = JSON.parse(data);
    if(!(coursesJson.result ==="success")) {
        document.getElementById("coursesList").innerHTML = data.error;
    } else {
        var courseList = coursesJson['teacherCourses'];
        var str = "";
        for (var i = 0; i < courseList.length; i++) {
            str += "<div class=\"col-md-3 col-sm-6  course\">";
            str += "<a class=\"course-box\" href=\"courses/show.html?courseId=" + courseList[i].teacherId + "\">";
            str += "<div class=\"sign-box\">";
            str += "<i class=\"fa fa-star-o course-follow pull-right\"";
            str += "data-follow-url=\"/courses/1/follow\"";
            str += "data-unfollow-url=\"/courses/1/unfollow\"  style=\"display:none\"  ></i>";
            str += "</div>";
            str += "<div class=\"course-img\">";
            str += "<img alt=\"" + courseList[i].name + "\" src=\"" + courseList[i].imgWebUrl + "\">";
            str += "</div>";
            str += "<div class=\"course-body\">";
            str += "<span class=\"course-title\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"" + courseList[i].name + "\">" + courseList[i].name + "</span>";
            str += "</div>";
            str += "<div class=\"course-footer\">";
            str += "<span class=\"course-per-num pull-left\">";
            // str += "<i class=\"fa fa-users\"></i>";
            str += "最后修改于：" + courseList[i].modificationTime.split(".")[0];
            str += "</span>";
            str += "</div>";
            str += "</a>";
            str += "</div>";
        }
        document.getElementById("coursesList").innerHTML = str;
        if(courseList.length >= 4) {
            var moreCourses = "<div class=\"pull-right watch-all\">";
            moreCourses += "<a href=\"courses/index.html\">查看更多 ></a>";
            moreCourses += "</div>";
            document.getElementById("moreCourses").innerHTML = moreCourses;
        }
    }
}

function getCoursesCountByTab() {
    var coursesTab = ["Python", "C/C++", "信息安全", "Linux", "Java", "PHP", "HTML5", "NodeJS", "Docker"];
    var obj = new Object();
    obj.coursesTab = coursesTab + "";
    var token = getCookie("token");
    $.ajax({
        url: "/apis/course/get_courses_count_by_tab?coursesTab="+coursesTab,
        type: "GET",
        headers: {
            token: token //这里是Token
        },
        cache: false,//设置不缓存
        success: getCoursesCountByTabSuccess,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            showErrorInfo(XMLHttpRequest,textStatus,errorThrown);
        }
    });
}

function getCoursesCountByTabSuccess(data) {
    var obj = JSON.parse(data);
    var coursesCountList = obj['coursesCountList'];
    document.getElementById("pythonCoursesCount").innerHTML = coursesCountList[0];
    document.getElementById("cppCoursesCount").innerHTML = coursesCountList[1];
    document.getElementById("informationSafetyCoursesCount").innerHTML = coursesCountList[2];
    document.getElementById("linuxCoursesCount").innerHTML = coursesCountList[3];
    document.getElementById("javaCoursesCount").innerHTML = coursesCountList[4];
    document.getElementById("phpCoursesCount").innerHTML = coursesCountList[5];
    document.getElementById("html5CoursesCount").innerHTML = coursesCountList[6];
    document.getElementById("nodejsCoursesCount").innerHTML = coursesCountList[7];
    document.getElementById("dockerCoursesCount").innerHTML = coursesCountList[8];
}

/**
 * 请求当前教师的前五个课程
 */
function teacherGetCoursesTop5() {
    var token = getCookie("token");
    $.ajax({
        url: "/apis/course/get_my_courses_top_number?topNumber=5",
        type: "GET",
        cache: false,//设置不缓存
        headers: {
            token: token //这里是Token
        },
        success: teacherGetCoursesTop5Success,
        error: showErrorInfo
    });
}

/**
 * 得到当前教师的前五个课程
 * @param data
 */
function teacherGetCoursesTop5Success(data) {
    var data = JSON.parse(data);
    var courseList = data['teacherCourses'];
        if(data.result=="error: 没有课程！") {
            //当前教师没有有课程
            var str = "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "我的课程" +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class=''>" + "没有课程" + "</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>" +
                "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "欢迎您，" + userName +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='/home/index.html' >我的主页</a></li>" +
                "<li><a class='' href='/add_user/index.html' >添加用户</a></li>" +
                "<li><a class='' href='/back_stage/index.html' >后台管理</a></li>" +
                "<li><a class='' href='' onclick='signOut(); return false;' data-toggle='modal' data-target='#signOutModel'>退出登录</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>";
            document.getElementById("userInfo").innerHTML = str;
        } else {
            // 当前老师有课程
            var str = "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "我的课程" +
                "</a>" +
                "<ul class='dropdown-menu'>";
            //var courses = JSON.parse(data)['teacherCourses'];
            for(var i = 0; i < courseList.length; i++) {
                var course = courseList[i];
                str += "<li><a class='' href='/developer/course_information.html?courseID=" + course.teacherId + "'>" + course.name + "</a></li>";
            }
            if (courseList.length >= 5) {
                str += "<li><a class=''  href='/developer/index.html'>查看更多</a></li>" ;
            }
            str += "</ul>" +
                "</li>" +
                "</ul>" +
                "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "欢迎您，" + userName +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='/home/index.html' >我的主页</a></li>" +
                "<li><a class='' href='/add_user/index.html' >添加用户</a></li>" +
                "<li><a class='' href='/back_stage/index.html' >后台管理</a></li>" +
                "<li><a class='' href='' onclick='signOut(); return false;' data-toggle='modal' data-target='#signOutModel'>退出登录</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>";
            document.getElementById("userInfo").innerHTML = str;
        }
}

function gotoExperimentalReport() {
    releaseExperimentCharacteristic = false;
    gotoNodeManagementCharacteristic = false;
    gotoVideoManagementCharacteristic = false;
    gotoExperimentalReportCharacteristic = true;
    getUserInfo();
}

function gotoNodeManagement() {
    releaseExperimentCharacteristic = false;
    gotoExperimentalReportCharacteristic = false;
    gotoVideoManagementCharacteristic = false;
    gotoNodeManagementCharacteristic = true;
    getUserInfo();
}

$(document).ready(function () {
    var token = getCookie("token");
    if (token === "no") {
        // document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        // document.getElementById("userLogin").click();
    }else {
        $.ajax({
            url: "/apis/user/loginByToken",
            type: "POST",
            dataType:"json",
            contentType: "application/json;charset=UTF-8",
            headers: {
                token: token //这里是Token
            },
            cache: false,//设置不缓存
            success: getInitUserSuccess,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                showErrorInfo(XMLHttpRequest,textStatus,errorThrown);
            }
        });
        getCoursesTop4();
        getCoursesCountByTab();
    }
});
function getCookie(name) {
    var cookieValue = "no";
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
function setTokenToCookie(value) {
    var Days = 1; //此 cookie 将被保存 30 天
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = "token =" + escape(value) + ";expires=" + exp.toGMTString()+";path=http://10.10.44.137/";
}
function deleteCookie(key) {
    var date = new Date();
    date.setTime(date.getTime() - 1);
    var delValue = getCookie(key);
    if (!!delValue) {
        document.cookie = key+'='+delValue+';expires='+date.toGMTString();
    }
}

function sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}
